import { MapControls, OrbitControls } from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import { vec3 } from "@react-three/rapier";
import { Ref, useEffect, useRef, useState } from "react";
import { MOUSE, Vector2, Vector3 } from "three";
import type { MapControls as MapControlsImpl } from 'three-stdlib'


const MAX_DISTANCE = 500

export default function ChooseDisciplineCamera(props: {
    target: number[],
    minPan: Vector3,
    maxPan: Vector3
}) {
    const cameraRef = useRef<MapControlsImpl>(null)
    const [target, setTarget] = useState([0,0,0])
    const [newTarget, setNewTarget] = useState(props.target)

    useEffect(() => {
        if (props.target != target) {
            setNewTarget(props.target)
        }
    }, [props.target])

    useFrame((state, delta) => {
        const newTargetVector = new Vector3(newTarget[0], newTarget[1], newTarget[2])
        const targetVector = new Vector3(target[0], target[1], target[2])
        const smoothedTarget = new Vector3()
        if (cameraRef.current) {
            if (newTarget != target) {
                cameraRef.current.enablePan = false
                cameraRef.current.minDistance = cameraRef.current.getDistance()
                cameraRef.current.maxDistance = cameraRef.current.getDistance()
                cameraRef.current.minPolarAngle = cameraRef.current.getPolarAngle()
                cameraRef.current.maxPolarAngle = cameraRef.current.getPolarAngle()
                smoothedTarget.lerpVectors(cameraRef.current.target, newTargetVector, delta * 5)
                cameraRef.current.target.copy(smoothedTarget)
            }
            if (cameraRef.current.target.distanceTo(newTargetVector) < 2) {
                cameraRef.current.enablePan = true
                cameraRef.current.minDistance = 70
                cameraRef.current.maxDistance = 100
                cameraRef.current.minPolarAngle = Math.PI / 5
                cameraRef.current.maxPolarAngle = Math.PI / 2.5
                setTarget(newTarget)
            }
            cameraRef.current.target.clamp(props.minPan, props.maxPan)
        }
    })

    return (
        <MapControls
            //@ts-ignore
            ref={cameraRef}
            screenSpacePanning={false}
            minAzimuthAngle={-Math.PI + Math.PI / 4}
            maxAzimuthAngle={-Math.PI + Math.PI / 4}
            rotateSpeed={0.2}
            minDistance={70}
            maxDistance={100}
            minPolarAngle={Math.PI / 5}
            maxPolarAngle={Math.PI / 2.5}
        />
    )
}